package com.amkai.mobile.utils.manager.job;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.Context;

import com.amkai.mobile.common.job.MobileJob;
import com.amkai.mobile.common.job.MobileJobResult;
import com.amkai.mobile.common.job.util.ByteSerializer;
import com.amkai.mobile.utils.data.Constants;
import com.amkai.mobile.utils.data.MobileDb;

/**
 * 
 * @author peter
 *
 */
public class MobileServiceManager {

	@SuppressWarnings("unchecked")
	public static <T extends MobileJobResult> T processMobileJob(Context context, MobileJob job) throws Exception {

		T jobResult = null;

		SoapObject request = new SoapObject(Constants.NAMESPACE, Constants.PROCESSJOB_METHOD_NAME);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

		String bjob = ByteSerializer.serializeObject(job);
		request.addProperty("mobileJob", bjob);

		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(getConnectionUrl(context));
		androidHttpTransport.call(Constants.SOAP_ACTION, envelope);
		Object so = (Object) envelope.getResponse();

		jobResult = (T) ByteSerializer.deserializeObject(so.toString());

		return jobResult;
	}

	private static String getConnectionUrl(Context context) {
		String result = "";
		String host = MobileDb.getLoginParameter(context, Constants.SERVER);
		if (host.length() != 0) {
			result = Constants.URLPrefix + host + Constants.URLSuffix;
		}
		return result;
	}

}
